package com.tristia.resources.impl;

import java.util.List;

import javax.annotation.Resource;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.sun.jersey.api.NotFoundException;
import com.tristia.dao.GenericDao;
import com.tristia.entity.Cd;

@Component
@Scope("request")
//@Path("/cddefault")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.APPLICATION_ATOM_XML })
public class CdResWs {
	@Resource
	GenericDao<Cd, Long> cdDao;
	@Context 
	UriInfo ui;
	@Context
	Request request;
	private String id = "2"; 
	private Logger log = Logger.getLogger(this.getClass());
	
	public CdResWs(){
	}
	
	public CdResWs(UriInfo ui, Request request, String id) {
        this.ui = ui;
        this.request = request;
        this.id = id;
    }
	
	public CdResWs(GenericDao<Cd, Long> cdDao, UriInfo ui, Request request, String id) {
		this.cdDao = cdDao;
        this.ui = ui;
        this.request = request;
        this.id = id;  
    }
	
	@GET
	public Cd getCd() {
		log.info("Hit getCd");
		log.info("ID: "+id);
		if (cdDao == null || id == null) {
			if (cdDao == null) log.info("CdDao is null");
			if (id == null) log.info("id is null");
			throw new NotFoundException("CdDao/id is null");
		} else {
			Cd cd = cdDao.get(Long.parseLong(id));
			if (cd == null)throw new NotFoundException("Cd not found");
			log.info("Sending: \n\n" + cd.toString() + "\n\n");
			return cd;
		}
	}
	
	@DELETE
	public void deleteCd(@PathParam("id") String id) {
		if(id!=null) {
			deleteCdById(id);
		}
		
		MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
		List<String> ids = queryParams.get("id");
		if(ids == null) {
			log.info("\n\nThe ids is null");
		} else {
			for (String currentid : ids) {
				deleteCdById(currentid);
			}
		}
	}

	private void deleteCdById(String id) {
		log.info("Delete Id: " + id);
		Cd cd = cdDao.get(Long.parseLong(id));
		if (cd == null) {
			log.info("Null was returned for ID: " + id);
		} else {
			cdDao.remove(Long.parseLong(id));
			log.info("Deleted the CD with ID:" + id);
		}
	}
	
	@Path("/{tracks}")
    public TracksResWs getItemResource() {
    	log.info("TracksResWs entered");
		return new TracksResWs(cdDao, ui, request, id);
    }
}
